﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TM.QWeibo.Client;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;

namespace TM.QWeibo.Client.Tweet
{
    public partial class Detail : PhoneApplicationPage
    {
        public Detail()
        {
            InitializeComponent();
            tweetDetail.SelectedSource = SelectSourceTweet;
            tweetDetail.ViewVideo = ViewTweetVideo;
            tweetDetail.ViewImage = ViewTweetImage;
            UserInfo.TapAvatar = ViewPersionInfo;
            replyList.Selected = SelectTweet;
            replyList.MenuItemClick = MenuItemClick;
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackgroundColor"];
        }

        public SDK.Objects.Tweet currentTweet { get; set; }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.ContainsKey(AppSetting.TweetIdParameterKey))
            {
                var tid = NavigationContext.QueryString[AppSetting.TweetIdParameterKey];
                if (!string.IsNullOrWhiteSpace(tid))
                {
                    progressBar.IsIndeterminate = true;
                    tweetDetail.LoadTweet(tid,BeforeLoading,LoadedTweetInfo);
                }
            }
        }

        private void LoadedTweetInfo(TM.QWeibo.SDK.Objects.Tweet t) {

            currentTweet = t;

            var userinfo = new TM.QWeibo.SDK.Objects.UserInfo
            {
                Name = t.Name,
                NickName = t.NickName,
                Head = t.Head,
                IsVip = t.IsVip
            };

            Dispatcher.BeginInvoke(() => {
                UserInfo.BindInfo(userinfo);
                //我的微博添加删除按钮
                if (t.Self == SDK.Objects.Tweet.ESelf.Yes && this.ApplicationBar.MenuItems.Count<4)
                {
                    var delbtn = new ApplicationBarMenuItem
                    {
                        Text = "删除微博"
                    };
                    delbtn.Click += btnDelete_Click;
                    this.ApplicationBar.MenuItems.Add(delbtn);
                }
            });
            progressBar.IsIndeterminate = false;
        }

        /// <summary>
        /// 删除微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            Dal.Tweet.Instance.Delete(currentTweet.Id, DeleteTweetCallback);
        }

        /// <summary>
        /// 删除微博的回调
        /// </summary>
        /// <param name="rs"></param>
        private void DeleteTweetCallback(bool rs) {
            if (rs)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    if (NavigationService.CanGoBack)
                    {
                        NavigationService.GoBack();
                    }
                });
            }
            else {
                (new Helper.MessageBoxHelper()).Show("删除失败！", "出错了", this.LayoutRoot);
            }
        }

        /// <summary>
        /// 选择父微博事件
        /// </summary>
        /// <param name="sourceid"></param>
        private void SelectSourceTweet(string sourceid) {
            if (!string.IsNullOrWhiteSpace(sourceid)) {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Detail.xaml?{0}={1}", AppSetting.TweetIdParameterKey, sourceid), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 播放微博的视频
        /// </summary>
        /// <param name="videourl"></param>
        private void ViewTweetVideo(string videourl)
        {
            if (!string.IsNullOrWhiteSpace(videourl))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Video.xaml?{0}={1}", AppSetting.TweetVideoParameterKey, videourl), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 播放微博的图片
        /// </summary>
        /// <param name="url"></param>
        private void ViewTweetImage(string url)
        {
            if (!string.IsNullOrWhiteSpace(url))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Image.xaml?{0}={1}", AppSetting.TweetImageParameterKey, url), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 查看用户资料
        /// </summary>
        /// <param name="name"></param>
        private void ViewPersionInfo(string name)
        {
            if (!string.IsNullOrWhiteSpace(name))
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Profile.xaml?{0}={1}", AppSetting.UserNameParameterKey, name), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 回复微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReply_Click(object sender, EventArgs e)
        {
            Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey,currentTweet);
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Reply.GetHashCode()), UriKind.Relative));
        }

        /// <summary>
        /// 对话微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnComment_Click(object sender, EventArgs e)
        {
            Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, currentTweet);
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Comment.GetHashCode()), UriKind.Relative));
        }

        /// <summary>
        /// 转播微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnForward_Click(object sender, EventArgs e)
        {
            Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, currentTweet);
            NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.ReAdd.GetHashCode()), UriKind.Relative));
        }
        /// <summary>
        /// 收藏微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFavorite_Click(object sender, EventArgs e)
        {
            Dal.Tweet.Instance.AddFavorite(currentTweet.Id, (rs) => {
                 (new Helper.MessageBoxHelper()).Show("收藏" + (rs ? "成功" : "失败"),"提示", this.LayoutRoot);
            });
        }

        private void mHome_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void mSms_Click(object sender, EventArgs e)
        {
            var smsTask = new SmsComposeTask();
            smsTask.Body = currentTweet.Origtext;
            smsTask.Show();
        }

        private void mEmail_Click(object sender, EventArgs e)
        {
            var emailTask = new EmailComposeTask();
            emailTask.Subject = "分享微博";
            emailTask.Body = currentTweet.Origtext;
            emailTask.Show();
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (detailPivot.SelectedIndex == 1) {
                replyList.Init(currentTweet.Id,BeforeLoading,AfterLoaded);
            }
        }

        /// <summary>
        /// 加载数据前显示loading状态
        /// </summary>
        private void BeforeLoading()
        {
            Dispatcher.BeginInvoke(() => progressBar.IsIndeterminate = true);
        }
        /// <summary>
        /// 加载数据后隐藏loading状态，显示相关信息
        /// </summary>
        private void AfterLoaded(object count)
        {
            Dispatcher.BeginInvoke(() =>
            {
                progressBar.IsIndeterminate = false;
            });
        }

        /// <summary>
        /// 选中微博，跳转到详细页
        /// </summary>
        /// <param name="t"></param>
        private void SelectTweet(SDK.Objects.Tweet t)
        {
            if (t != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/Tweet/Detail.xaml?{0}={1}", AppSetting.TweetIdParameterKey, t.Id), UriKind.Relative)));
            }
        }

        /// <summary>
        /// 控件弹出菜单服务
        /// </summary>
        /// <param name="t"></param>
        /// <param name="act"></param>
        private void MenuItemClick(SDK.Objects.Tweet t, Helper.EMenuItemAction act)
        {
            if (act == Helper.EMenuItemAction.Reply)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Reply.GetHashCode()), UriKind.Relative));
            }
            else if (act == Helper.EMenuItemAction.ReAdd)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.ReAdd.GetHashCode()), UriKind.Relative));
            }
            else if (act == Helper.EMenuItemAction.Favorite)
            {

                Dal.Tweet.Instance.AddFavorite(t.Id, (rs) =>
                {
                    (new Helper.MessageBoxHelper()).Show("收藏" + (rs ? "成功" : "失败"), "提示", this.LayoutRoot);
                });

            }
            else if (act == Helper.EMenuItemAction.Comment)
            {
                Common.Isolated.Set(Helper.IsolatedHelper.TargetTweetKey, t);
                NavigationService.Navigate(new Uri(string.Format("/Tweet/Add.xaml?{0}={1}", AppSetting.AddTweetTypeParameterKey, Helper.EAddTweetType.Comment.GetHashCode()), UriKind.Relative));
            }
        }

    }
}
